/*
 * Copyright 2010 Pierre Heinzerling, Uwe Janner, Patrick Wright
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const TOOLINSKY_GAE_SERVER = "http://latest.publinksky.appspot.com";
//const TOOLINSKY_GAE_SERVER = "http://localhost:8080";
const TOOLINSKY_GAE_HOST = TOOLINSKY_GAE_SERVER + "/publinksky";

function serverListUserThemes(onListCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/theme/list/ownedBy";
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var jsres = JSON.parse(response);

            // is array of themes
            if (jsres.length == 0) {
                onListCallback(jsres);
            } else {
                onListCallback(jsres);
            }
        } else {
            logEmptyResponse(req);
            onListCallback(null);
        }
    };
    req.send(null);
}

function serverListModifiedThemes(onLoadCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/theme/list/modified";
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var themes = JSON.parse(response);
            onLoadCallback(themes);
        } else {
            logEmptyResponse(req);
            onLoadCallback(null);
        }
    };
    req.send(null);
}

function serverGetTheme(themeLocalCopy, themeId, onLoadCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/theme/get/" + themeId;
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var themeAndInvitation = JSON.parse(response);
            var theme = themeAndInvitation.theme;
            onLoadCallback(themeAndInvitation);
            return;
        } else {
            logEmptyResponse(xhrUrl, req);
            if (themeLocalCopy) {
                onLoadCallback(themeLocalCopy);
            }
            return;
        }
    };
    req.send(null);
}

function serverGetThemeScratchpad(forEmail, onLoadCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/theme/get/scratchpad";
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var theme = JSON.parse(response);
            onLoadCallback(theme);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
    };
    req.send(null);
}

function serverAddTheme(name, onAddCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/theme/add?name=" + name;
    writeLog("XHR: " + xhrUrl);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var theme = JSON.parse(response);
            onAddCallback(theme);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
    };
    req.send(null);
}

function serverListAllThemeInvitations(theme, onListCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/invitation/list/theme?themeId=" + theme.key.id;
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var jsres = JSON.parse(response);

            // is array of themes
            if (jsres.length == 0) {
                onListCallback(jsres);
            } else {
                onListCallback(jsres);
            }
        } else {
            logEmptyResponse(req);
            onListCallback(null);
        }
    };
    req.send(null);
}

function serverListThemeInvitationsTo(onListCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/invitation/list/to";
    writeLog("XHR: " + xhrUrl);
    req.open("GET", xhrUrl, true);
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var jsres = JSON.parse(response);

            // is array of themes
            if (jsres.length == 0) {
                onListCallback(jsres);
            } else {
                onListCallback(jsres);
            }
        } else {
            logEmptyResponse(req);
            onListCallback(null);
        }
    };
    req.send(null);
}

function serverAddInvitation(theme, toEmail, onDoneCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/invitation/add?themeId=" + theme.key.id + "&toEmail=" + toEmail;
    writeLog("XHR " + xhrUrl + " theme " + theme.key.id);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var invite = JSON.parse(response);
            onDoneCallback(theme, invite);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
    };
    req.send(null);
}

function serverDeclineInvitation(theme, onDoneCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/invitation/decline?themeId=" + theme.key.id;
    writeLog("XHR " + xhrUrl);
    req.open("POST", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (!response) {
            logEmptyResponse(xhrUrl, req);
        }
        onDoneCallback(theme);
    };
    req.send(null);
}

function serverFindLink(forTheme, forUrl, onFindCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/link/find";
    writeLog("XHR " + xhrUrl + " theme " + forTheme.key.id);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var link = JSON.parse(response);
            onFindCallback(link);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
    };
    req.send(JSON.stringify({themeId: forTheme.key.id, uriString: forUrl}));
}

function serverSubmitLink(themeId, url, title, note, tagCsv, tags, onDoneCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/link/submit";
    writeLog("XHR " + xhrUrl + " theme " + themeId);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        var val;
        if (response) {
            val = JSON.parse(response);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
        onDoneCallback(val);
    };
    req.send(JSON.stringify({themeId: themeId, uriString: url, title: title, note: note}));
}

function serverListLinksForTheme(themeId, listLinkCallback, onDoneCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/link/list/" + themeId;
    writeLog("XHR " + xhrUrl);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var cnt = 0;
            var linkAndComments = JSON.parse(response);
            if (linkAndComments.length == 0) {
                listLinkCallback(null, null);
            } else {
                cnt = linkAndComments.length;
                var i;
                for (i = 0; i < cnt; i++) {
                    var lac = linkAndComments[i];
                    var link = lac.link;
                    listLinkCallback(link, lac.linkComments);
                }
            }
            if (onDoneCallback) onDoneCallback(cnt);
        } else {
            logEmptyResponse(xhrUrl, req);
            listLinkCallback(null, null);
            if (onDoneCallback) onDoneCallback(0);
        }
    };
    req.send(null);
}

function serverFindCommentsForLink(link, onDoneCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/comment/list";
    writeLog("XHR PUT " + xhrUrl);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var jsres = JSON.parse(response);
            if (jsres.length == 0) {
                onDoneCallback(null);
            } else {
                if (onDoneCallback) onDoneCallback(jsres);
            }
        } else {
            logEmptyResponse(xhrUrl, req);
            onDoneCallback(null);
        }
    };
    req.send(JSON.stringify({themeId: link.theme.id, uriString: link.uriString}));
}

function serverDeleteLink(linkId, onDeleteCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/link/delete?linkId=" + linkId;
    writeLog("XHR " + xhrUrl);
    req.open("PUT", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            onDeleteCallback(JSON.parse(response));
        } else {
            logEmptyResponse(xhrUrl, req);
            onDeleteCallback(null);
        }
    };
    req.send(null);
}

function serverIncrementVisitCount(themeId, uriString, onUpdatedCallback) {
    var req = new XMLHttpRequest();
    var xhrUrl = TOOLINSKY_GAE_HOST + "/link/visit?themeId=" + themeId + "uriString=" + uriString;
    writeLog("XHR " + xhrUrl);
    req.open("POST", xhrUrl, true);
    req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    req.onload = function() {
        var response = req.responseText;
        if (response) {
            var reply = JSON.parse(response);
            onUpdatedCallback(reply.visited);
        } else {
            logEmptyResponse(xhrUrl, req);
        }
    };
    req.send(null);
}

function logEmptyResponse(xhrUrl, req) {
    writeLog(xhrUrl + ": empty response from server, status " + req.statusText + "(" + req.status + ")");
}

